<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 头部搜索栏 -->
    <view class="header">
      <view class="search-box">
        <image class="search-icon" src="/static/icons/search.png"></image>
        <input 
          type="text" 
          v-model="searchText" 
          placeholder="搜索消息" 
          placeholder-class="placeholder"
          confirm-type="search"
          @confirm="searchMessages"
          @input="onSearchInput"
        />
        <view class="search-clear" v-if="searchText" @tap="clearSearch">
          <image class="clear-icon" src="/static/icons/x-circle.png"></image>
        </view>
      </view>
    </view>
    
    <!-- 消息列表内容区域 -->
    <view class="content-container">
      <scroll-view 
        scroll-y 
        class="message-list" 
        @scrolltolower="loadMoreChats" 
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh"
      >
        <!-- 未读消息分组 -->
        <block v-if="unreadChats.length > 0">
          <view class="list-section-header">
            <text class="section-title">未读消息</text>
          </view>
          <view class="chat-list">
            <view 
              class="chat-item" 
              v-for="chat in unreadChats" 
              :key="chat.id" 
              @tap="openChat(chat)"
            >
              <view class="chat-avatar">
              <!--  <image class="avatar" :src="chat.avatar || '/static/avatars/default.png'"></image> -->
                <view class="unread-badge" v-if="chat.unreadCount > 0">
                  {{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
                </view>
              </view>
              <view class="chat-content">
                <view class="chat-header">
                  <text class="chat-name">{{ chat.FromUserID }}</text>
                  <text class="chat-time">{{ formatTime(chat.timestamp) }}</text>
                </view>
                <!-- <view class="chat-body">
                  <text class="chat-message">{{ chat.lastMsg }}</text>
                  <view class="chat-status" v-if="chat.isMuted">
                    <image class="status-icon" src="/static/icons/volume-x.png"></image>
                  </view>
                </view> -->
              </view>
            </view>
          </view>
        </block>
        
        <!-- 所有消息 -->
        <view class="list-section-header">
          <text class="section-title">全部消息</text>
        </view>
        <view class="chat-list">
          <view 
            class="chat-item" 
            v-for="chat in readChats" 
            :key="chat.id" 
            @tap="openChat(chat)"
          >
            <view class="chat-avatar">
              <image class="avatar" :src="chat.avatar || '/static/avatars/default.png'"></image>
              <view class="unread-badge" v-if="chat.unreadCount > 0">
                {{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
              </view>
            </view>
            <view class="chat-content">
              <view class="chat-header">
                <text class="chat-name">{{ chat.name }}</text>
                <text class="chat-time">{{ formatTime(chat.lastMsgTime) }}</text>
              </view>
              <view class="chat-body">
                <text class="chat-message">{{ chat.content }}</text>
                <view class="chat-status" v-if="chat.isMuted">
                  <image class="status-icon" src="/static/icons/volume-x.png"></image>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-more" v-if="isLoading">
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 无数据状态 -->
        <view class="empty-state" v-if="allChats.length === 0 && !isLoading">
          <image class="empty-icon" src="/static/icons/message-circle.png"></image>
          <text class="empty-text">暂无消息</text>
          <text class="empty-desc">您还没有收到任何消息</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view class="tab-item" @tap="navigateTo('/pages/index/index')">
        <image class="tab-icon" src="/static/icons/home.png"></image>
        <text class="tab-text">首页</text>
      </view>
      <view class="tab-item" @tap="navigateTo('/pages/project/project-list')">
        <image class="tab-icon" src="/static/icons/briefcase.png"></image>
        <text class="tab-text">项目</text>
      </view>
      <view class="tab-item active">
        <image class="tab-icon" src="/static/icons/message-circle-fill.png"></image>
        <text class="tab-text">消息</text>
      </view>
      <view class="tab-item" @tap="navigateTo('/pages/profile/profile')">
        <image class="tab-icon" src="/static/icons/user.png"></image>
        <text class="tab-text">我的</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onActivated ,watch} from 'vue'
import { debounce } from 'lodash-es'
import { useMainStore } from '@/store'
const store = useMainStore()
// 响应式状态
const chats = ref([])
const isLoading = ref(false)
const isRefreshing = ref(false) 
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const searchText = ref('')
const searchResults = ref([])

// 计算属性
const allChats = computed(() => 
  searchText.value ? searchResults.value : chats.value
)
const unreadChats = computed(() => 
  // allChats.value.filter(chat => chat.unreadCount > 0)
  allChats.value
)
// const readChats = computed(() => 
//   allChats.value.filter(chat => chat.unreadCount === 0)
// )

// 生命周期钩子
onMounted(() => {
  // loadChats()
})

onActivated(() => {
  refreshChats()
})

// 方法
// const loadChats = async () => {
//   if (isLoading.value || !hasMore.value) return
  
//   isLoading.value = true
  
//   try {
//     const mockData = await getMockChats()
    
//     if (page.value === 1) {
//       chats.value = mockData
//     } else {
//       chats.value = [...chats.value, ...mockData]
//     }
    
//     hasMore.value = mockData.length === pageSize.value
//     page.value++
//   } catch (error) {
//     console.error('加载消息失败:', error)
//     uni.showToast({
//       title: '加载失败',
//       icon: 'none'
//     })
//   } finally {
//     isLoading.value = false
//     isRefreshing.value = false
//   }
// }

// const loadMoreChats = () => {
//   loadChats()
// }

// const refreshChats = () => {
//   page.value = 1
//   hasMore.value = true
//   loadChats()
// }

const onRefresh = () => {
  isRefreshing.value = true
  refreshChats()
}

const searchMessages = () => {
  if (!searchText.value.trim()) {
    searchResults.value = []
    return
  }
  
  const keyword = searchText.value.toLowerCase()
  searchResults.value = chats.value.filter(chat => 
    chat.name.toLowerCase().includes(keyword) || 
    chat.lastMsg.toLowerCase().includes(keyword)
  )
}

const onSearchInput = debounce(searchMessages, 300)

const clearSearch = () => {
  searchText.value = ''
  searchResults.value = []
}
watch(()=>
	store.messages
,(newVal)=>{
	console.log("消息列表界面")
	console.log("有新消息来了！",newVal)
	chats.value = newVal
},
{deep:true})

const openChat = (chat) => {
	console.log("chat有什么：",chat)
  uni.navigateTo({
    url: `/pages/chat/chat-detail?id=${chat.id}&name=${encodeURIComponent(chat.FromUserID)}`
  })
}

const navigateTo = (url) => {
  uni.switchTab({ url })
}

const formatTime = (timestamp) => {
  const now = new Date()
  const msgDate = new Date(timestamp)
  const diffDays = Math.floor((now - msgDate) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return msgDate.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit',
      hour12: false
    }).replace(/^0/, '')
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return weekDays[msgDate.getDay()]
  } else {
    return `${msgDate.getMonth() + 1}月${msgDate.getDate()}日`
  }
}

// const getMockChats = () => {
//   return new Promise(resolve => {
//     () => {
		
      // const mockAvatars = [
      //   '/static/avatars/avatar1.png',
      //   '/static/avatars/avatar2.png',
      //   '/static/avatars/avatar3.png',
      //   '/static/avatars/avatar4.png'
      // ]
      
      // const mockNames = [
      //   '上海建筑设计院',
      //   '城市规划设计所',
      //   '绿色建筑咨询',
      //   '智能建筑系统',
      //   '现代景观设计',
      //   '结构工程团队'
      // ]
      
      // const mockMessages = [
      //   '您好，关于项目进度我们需要进一步沟通',
      //   '已收到您的投标方案，非常感谢',
      //   '请问您能提供更详细的技术参数吗？',
      //   '项目会议定于下周三下午2点',
      //   '预算方案已批准，请查收相关文件'
      // ]
      
      // const result = Array.from({ length: pageSize.value }, (_, i) => {
      //   const id = `chat_${page.value}_${i}`
      //   const randomTime = new Date()
      //   randomTime.setHours(randomTime.getHours() - Math.floor(Math.random() * 240))
        
   //      return {
			// FromUserID:
          // id,
          // name: mockNames[Math.floor(Math.random() * mockNames.length)],
          // avatar: mockAvatars[Math.floor(Math.random() * mockAvatars.length)],
          // lastMsg: mockMessages[Math.floor(Math.random() * mockMessages.length)],
          // lastMsgTime: randomTime.getTime(),
          // unreadCount: Math.random() > 0.7 ? Math.floor(Math.random() * 10) : 0,
          // isMuted: Math.random() > 0.8
		  
//         }
//       })
      
//       // resolve(result)
//     }
//   })
// }
</script>


<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f9fa;
}

.status-bar {
  height: var(--status-bar-height);
  width: 100%;
  background-color: #1d4ed8;
}

.header {
  background-color: #1d4ed8;
  padding: 16rpx 24rpx;
  flex-shrink: 0;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 40rpx;
  padding: 12rpx 20rpx;
  
  input {
    flex: 1;
    height: 56rpx;
    color: #fff;
    font-size: 28rpx;
    line-height: 56rpx;
  }
  
  .placeholder {
    color: rgba(255, 255, 255, 0.7);
  }
}

.search-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 12rpx;
  opacity: 0.8;
}

.search-clear {
  width: 36rpx;
  height: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-icon {
  width: 36rpx;
  height: 36rpx;
  opacity: 0.8;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.message-list {
  flex: 1;
  height: 100%;
  background-color: #f8f9fa;
}

.list-section-header {
  padding: 16rpx 24rpx 8rpx;
  background-color: #f8f9fa;
}

.section-title {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.chat-list {
  background-color: #fff;
}

.chat-item {
  display: flex;
  padding: 20rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
  
  &:active {
    background-color: #f5f5f5;
  }
}

.chat-avatar {
  position: relative;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #eee;
}

.unread-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  min-width: 36rpx;
  height: 36rpx;
  background-color: #f56565;
  color: #fff;
  border-radius: 18rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.chat-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6rpx;
}

.chat-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.chat-time {
  font-size: 24rpx;
  color: #999;
  flex-shrink: 0;
  margin-left: 16rpx;
}

.chat-body {
  display: flex;
  align-items: center;
}

.chat-message {
  font-size: 26rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.chat-status {
  margin-left: 12rpx;
  flex-shrink: 0;
}

.status-icon {
  width: 28rpx;
  height: 28rpx;
  opacity: 0.5;
}

.loading-more {
  text-align: center;
  padding: 24rpx 0;
}

.loading-text {
  font-size: 26rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  text-align: center;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.3;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #666;
  margin-bottom: 8rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
}

.tab-bar {
  height: calc(100rpx + env(safe-area-inset-bottom));
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #fff;
  display: flex;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8rpx 0;
  
  &.active {
    .tab-text {
      color: #1d4ed8;
    }
  }
}

.tab-icon {
  width: 44rpx;
  height: 44rpx;
  margin-bottom: 4rpx;
}

.tab-text {
  font-size: 22rpx;
  color: #999;
}

/* 适配小屏幕设备 */
@media (max-width: 360px) {
  .chat-name {
    font-size: 28rpx;
  }
  
  .chat-message {
    font-size: 24rpx;
  }
  
  .chat-item {
    padding: 16rpx 20rpx;
  }
}
</style>